import { Inject, Post, Body, Get, Query } from '@midwayjs/core';
import { CoolController, BaseController, TagTypes, CoolUrlTag, CoolCommException } from '@cool-midway/core';
import { OrderInfoEntity } from '../../entity/info';
import { OrderInfoService } from '../../service/info';
import { StudentStudentEntity } from '../../../student/entity/student';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, DataSource  } from 'typeorm';


/**
 * 订单信息
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['payNotify', 'payNotifyYanjiao', 'payNotifyFangshan', 'payNotifyYizhuang']
})
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderInfoEntity,
  // 向表插入当前登录用户ID
  insertParam: async (ctx) => {
    if (!ctx.request.body.shopId || ctx.request.body.shopId === '') {
      throw new CoolCommException('请联系管理员绑定店铺');
    }
    const now = new Date();
    // 生成格式：年月日时分秒+4位随机数
    const orderNumber = 
      now.getFullYear().toString() +
      (now.getMonth() + 1).toString().padStart(2, '0') +
      now.getDate().toString().padStart(2, '0') +
      now.getHours().toString().padStart(2, '0') +
      now.getMinutes().toString().padStart(2, '0') +
      now.getSeconds().toString().padStart(2, '0') +
      Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return {
      orderNumber: orderNumber,
    };
  },
  service: OrderInfoService,
  pageQueryOp: {
    keyWordLikeFields: ['a.orderNumber', 'a.phone'],
    fieldEq: ['a.status', 'a.payType', 'b.phone', 'b.name', 'a.shopId'],
    fieldLike: [],
    where: async ctx => {
      const { startTime, endTime } = ctx.request.body;
      const where = [];
      if (startTime) {
        where.push(['a.orderTime >= :startTime', { startTime }]);
      }
      if (endTime) {
        where.push(['a.orderTime <= :endTime', { endTime }]);
      }
      return where;
    },
    join: [
      {
        entity: StudentStudentEntity,
        alias: 'b',
        condition: 'a.userId = b.id',
        type: 'leftJoin',
      },
      {
        entity: BaseSysUserEntity,
        alias: 'c',
        condition: 'a.sales = c.id',
        type: 'leftJoin',
      },
    ],
    select: ['a.*', 'b.name as userName', 'b.phone as userPhone', 'c.name as salesName', 'b.source as userSource'],
  },
})
export class AdminOrderInfoController extends BaseController {
  @Inject()
  orderInfoService: OrderInfoService;

  @Inject()
  ctx;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @Get('/checkPayStatus', { summary: '检查订单支付状态' })
  async checkPayStatus(@Query('orderId') orderId: number) {
    return this.ok(await this.orderInfoService.checkPayStatus(orderId));
  }

  @Post('/cancelPay', { summary: '取消支付' })
  async cancelPay(@Body() param: { orderId: number }) {
    return this.ok(await this.orderInfoService.cancelPay(param.orderId));
  }

  @Post('/payQrcode', { summary: '生成支付二维码' })
  async payQrcode(@Body() param: { orderId: number }) {
    const result = await this.orderInfoService.payQrcode(param.orderId);
    return this.ok(result);
  }

  @Post('/payNotify', { summary: '微信支付回调北京双博视' })
  async payNotify(@Body() body) {
    const shopId = 0;
    const result = await this.orderInfoService.handleWxPayNotify(body, shopId);
    return this.ok(result);
  }

  @Post('/payNotifyYanjiao', { summary: '微信支付回调燕郊' })
  async payNotifyYanjiao(@Body() body) {
    const shopId = 77;
    const result = await this.orderInfoService.handleWxPayNotify(body, shopId);
    return this.ok(result);
  }

  @Post('/payNotifyFangshan', { summary: '微信支付回调房山' })
  async payNotifyFangshan(@Body() body) {
    const shopId = 78;
    const result = await this.orderInfoService.handleWxPayNotify(body, shopId);
    return this.ok(result);
  }

  @Post('/payNotifyYizhuang', { summary: '微信支付回调亦庄' })
  async payNotifyYizhuang(@Body() body) {
    const shopId = 79;
    const result = await this.orderInfoService.handleWxPayNotify(body, shopId);
    return this.ok(result);
  }
}
